package com.zdkj.subway.check.controller.subwayRat.cashBoxBatchAudit;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.check.entity.*;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.*;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.service.SwAuTvmBoxAmountDifferenceService;
import com.zdkj.subway.check.service.impl.subwayRat.cashBoxBatchAudit.CashBoxBatchAuditServiceImpl;
import com.zdkj.subway.check.util.DateFormat;
import com.zdkj.subway.check.util.JdbcUtil;
import com.zdkj.subway.check.util.LineOrStation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 报表差错信息
 */
@RestController
@RequestMapping("/check")
@Api(value = "check",tags = "TVM分钱箱审核")
@Slf4j
public class CashBoxBatchAuditController {

    @Autowired
    private CashBoxBatchAuditServiceImpl cashBoxBatchAuditService;
    @Resource
    SwAuTvmBoxAmountDifferenceMapper swAuTvmBoxAmountDifferenceMapper;
    @Resource
    SwAuTvmAmountDefferenceMapper swAuTvmAmountDefferenceMapper;
    @Resource
    private SwAuTvmBoxAmountDifferenceService swAuTvmBoxAmountDifferenceService;
    @Autowired
    private CashBoxBatchAuditMapper cashBoxBatchAuditMapper;
    @Resource
    SwAuTvmBoxAmountDifferenceLogMapper swAuTvmBoxAmountDifferenceLogMapper;
    @Resource
    private SwStReportErrorAlterAppayMapper swStReportErrorAlterAppayMapper;
    @Resource
    private SwStReportErrorAlterAppayDetailMapper swStReportErrorAlterAppayDetailMapper;

    /**
     * TVM分钱箱审核查询
     * @param page
     * @param param 列表查询传入的参数
     * @return
     * @throws ParseException
     */
    @ApiOperation(value = "TVM分钱箱审核查询", notes = "TVM分钱箱审核查询")
    @RequestMapping("/getDifferencesInAudit")
    public R getDifferencesInAudit(com.baomidou.mybatisplus.extension.plugins.pagination.Page page, @RequestParam Map<String, Object> param) throws ParseException {
        PigxUser user = SecurityUtils.getUser();
        if(user.getBelongToLine()){
            List lineList = LineOrStation.getmanagementLine();
            param.put("lines",lineList);
        }else{
            List lineList = LineOrStation.getLineOrManagementLine();
            param.put("lines",lineList);
        }
        //TVM票款差异分钱箱差异审核
        IPage<CashBoxBatchAudit> cashboxUninstallList = cashBoxBatchAuditService.getDifferencesInAudit(page,param);
        List<CashBoxBatchAudit> records = cashboxUninstallList.getRecords();
        Date curr_date = new Date();
        String currdateStr = DateFormat.date_ex_str(curr_date,"yyyy-MM-dd")+" 00:00:00";
        Date currdate = DateFormat.panDuanDate(currdateStr);
        for (CashBoxBatchAudit record : records) {
            //线路+站点+TVM编号+收益日期+钱箱类型+报表名称（TVM钱箱清点记录）+ 除了审批不通过    查找TVM分钱箱审核
            List<SwStReportErrorAlterApply> applies =
                    swStReportErrorAlterAppayMapper.selectList(Wrappers.<SwStReportErrorAlterApply>lambdaQuery()
                            .eq(SwStReportErrorAlterApply::getLineCode, record.getLineCode())
                            .eq(SwStReportErrorAlterApply::getStationCode, record.getStationCode())
                            .eq(SwStReportErrorAlterApply::getTvmCode, record.getTvmCode())
                            .eq(SwStReportErrorAlterApply::getReprotTime, DateFormat.dateTOLocalDate(record.getRecordTime()))
                            .eq(SwStReportErrorAlterApply::getCashboxType, record.getCashBoxType())
				            .eq(SwStReportErrorAlterApply::getDelFlag, "0")
                            .eq(SwStReportErrorAlterApply::getReportNameId, "5")
                            .ne(SwStReportErrorAlterApply::getIsModify,"1")
                            .ne(SwStReportErrorAlterApply::getCheckStatus,"4"));
            List<SwStReportErrorAlterApply> collect = applies.stream().filter(s -> {
                if (s.getNoticeTime() != null) {
                    //利用Calendar 实现 Date日期 通知时间+期限 < 当前时间 过滤掉
                    Date date = null;
                    try {
                        //取到年月日
                        String dateStr = DateFormat.date_ex_str(s.getNoticeTime(),"yyyy-MM-dd")+" 00:00:00";
                        Date noticedate = DateFormat.panDuanDate(dateStr);
                        date = DateFormat.date_add_or_sub_days(noticedate, s.getModifyLimitTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    boolean b = date.compareTo(currdate) >= 0;
                    return b;

                }
                return true;
            }).collect(Collectors.toList());
            //都不是null 说明未完成
            if(CollectionUtil.isNotEmpty(collect)){
                record.setIsModify("0");//0代表待修改
            }else {
                record.setIsModify("1");//1代表已完成
            }
        }
        cashboxUninstallList.setRecords(records);
        return R.ok(cashboxUninstallList);
    }

    /**
     * 硬币钱箱列表根据id查询
     * @param param
     * @return
     */
    @ApiOperation(value = "硬币钱箱列表根据id查询", notes = "硬币钱箱列表根据id查询")
    @RequestMapping("/getListCionMOneyById") //硬币钱箱列表根据id查询
    public CashBoxBatchAudit getListCionMOneyById(@RequestParam Map<String, String> param){
        String cashBoxType = (param.get("cashBoxType"));
        String ids = param.get("id");
        CashBoxBatchAudit cashBoxBatchAudit = new CashBoxBatchAudit();
        CashBoxBatchAudit cashboxUninstallList;
        if("6".equals(cashBoxType)){
            cashboxUninstallList = cashBoxBatchAuditMapper.getTvmBoxByAmountId(ids);
        }else {
            cashBoxBatchAudit.setId(Long.parseLong(param.get("id")));
            cashboxUninstallList = cashBoxBatchAuditMapper.getDifferencesInAuditById(cashBoxBatchAudit);
        }
        return cashboxUninstallList;
    }

    /**
     * 硬币钱箱列表
     * @param page
     * @param param
     * @return
     */
    @ApiOperation(value = "硬币钱箱列表", notes = "硬币钱箱列表")
    @RequestMapping("/getListCionMOney") //硬币钱箱列表
    public R getListCionMOney(com.baomidou.mybatisplus.extension.plugins.pagination.Page page,@RequestParam Map<String, Object> param){
        PigxUser user = SecurityUtils.getUser();
        if(user.getBelongToLine()){
            List lineList = LineOrStation.getmanagementLine();
            param.put("lines",lineList);
        }else{
            List lineList = LineOrStation.getLineOrManagementLine();
            param.put("lines",lineList);
        }
        IPage<CashBoxBatchAudit> cashboxUninstallList = cashBoxBatchAuditMapper.getListCionMOney(page,param);
        return R.ok(cashboxUninstallList);
    }

    /**
     * 一键审核
     * @param param ids
     * @return
     */
    @ApiOperation(value = "一键审核",notes = "一键审核")
    @RequestMapping("/updateAuditStatus")
    public Map updateAuditStatus(@RequestParam Map<String,String> param){
        JSONArray ids = JSONObject.parseArray(param.get("ids"));
		PigxUser user = SecurityUtils.getUser();
        //TVM分钱箱审核一键审核
        cashBoxBatchAuditService.updateAuditStatus(ids,user);
        Map resp = new HashMap();
        resp.put("code","1");
        return resp;
    }

    /**
     * 加入票款差异协查
     * @param param ids
     * @return
     */
    @ApiOperation(value = "加入票款差异协查",notes = "加入票款差异协查")
    @RequestMapping("/insertSwAuTvmMoneyAssist")
    public Map insertSwAuTvmMoneyAssist(@RequestBody Map<String,String> param){
        JSONArray ids = JSONObject.parseArray(param.get("ids"));
        String remark = String.valueOf(param.get("remark"));
        //分钱箱加入票款协查
        cashBoxBatchAuditService.insertSwAuTvmMoneyAssist(ids, remark);
        Map resp = new HashMap();
        resp.put("code","1");
        return resp;
    }

    /**
     * 加入层级差异协查
     * @param param ids
     * @return
     */
    @ApiOperation(value = "加入层级差异协查",notes = "加入层级差异协查")
    @RequestMapping("/insertSwAuTvmCashboxAmountHierarchyDifference")
    public Map insertSwAuTvmCashboxAmountHierarchyDifference(@RequestParam Map<String,String> param){
        JSONArray ids = JSONObject.parseArray(param.get("ids"));
        //分钱箱加入层级协查
        cashBoxBatchAuditService.insertSwAuTvmCashboxAmountHierarchyDifference(ids);
        Map resp = new HashMap();
        resp.put("code","1");
        return resp;
    }

    /**
     * 获取手工清出金额
     * @param param
     * @return
     * @throws ParseException
     * @throws SQLException
     */
    @ApiOperation(value = "获取手工清出金额",notes = "获取手工清出金额")
    @RequestMapping("/getClearOutAmount")
    public Result getClearOutAmount(@RequestParam Map<String,String> param) throws ParseException, SQLException {
        Result res=new Result(ResultDetailMsg.OK);
        String start=param.get("incomeSettleBeginTime").substring(0,10)+" 02:00:00";
        String endStr=param.get("incomeSettleEndTime").substring(0,10)+" 01:59:59";
        Date end = DateFormat.date_add_or_sub_days(DateFormat.panDuanDate(endStr), 1);
        //根据时间范围从视图获取手工清出金额
        String sql="select ifnull(sum(clear_out_amount),0)*100 clear_out_amount,ifnull(sum(clear_out_paper_amount),0)*100 clear_out_paper_amount from view_sw_st_handwork_clean_record where " +
                "LINE_CODE='"+param.get("lineCode")+"' " +
                "and STATION_CODE= '"+param.get("stationCode")+"' " +
                "and TVM_CODE = '"+param.get("tvmCode")+"' " +
                "and CLEAN_TIME >='"+start+"' " +
                "and CLEAN_TIME <='"+DateFormat.date_ex_str(end,"yyyy-MM-dd HH:mm:ss")+"'";
        List<Map<String, Object>> maps = JdbcUtil.exeSqlQuery(sql);
        res.setData(maps);
        return res;
    }

    /**
     * 获取手工清出金额接口
     * @param swAuTvmBoxAmountDifference
     * @return
     * @throws ParseException
     * @throws SQLException
     */
    public Result getClearOutAmountOfReplace(SwAuTvmBoxAmountDifference swAuTvmBoxAmountDifference) throws ParseException, SQLException {
        Result res=new Result(ResultDetailMsg.OK);
        Date start=swAuTvmBoxAmountDifference.getIncomeSettleBeginTime();
        Date endStr=swAuTvmBoxAmountDifference.getIncomeSettleEndTime();
        //利用Calendar 实现 Date日期+1天
        Calendar c = Calendar.getInstance();
        c.setTime(endStr);
        c.add(Calendar.DAY_OF_MONTH, 1);
        endStr = c.getTime();
        String startTime=DateFormat.date_ex_str(start,"yyyy-MM-dd")+" 02:00:00";
        String endStrTime=DateFormat.date_ex_str(endStr,"yyyy-MM-dd")+" 01:59:59";
        String sql="select ifnull(sum(clear_out_amount),0)*100 clear_out_amount,ifnull(sum(clear_out_paper_amount),0)*100 clear_out_paper_amount from view_sw_st_handwork_clean_record where " +
                "LINE_CODE='"+swAuTvmBoxAmountDifference.getLineCode()+"' " +
                "and STATION_CODE= '"+swAuTvmBoxAmountDifference.getStationCode()+"' " +
                "and TVM_CODE = '"+swAuTvmBoxAmountDifference.getTvmCode()+"' " +
                "and CLEAN_TIME >='"+startTime+"' " +
                "and CLEAN_TIME <='"+endStrTime+"'";
        List<Map<String, Object>> maps = JdbcUtil.exeSqlQuery(sql);
        res.setData(maps);
        return res;
    }


    /**
     * 票款差异审核的分钱箱-列表-刷新
     * @param param
     * @return
     */
    @ApiOperation(value = "票款差异审核的分钱箱-列表-刷新",notes = "票款差异审核的分钱箱-列表-刷新")
    @RequestMapping("/syncCashBoxBatchAuditSystemAmounts")
    public Result syncCashBoxBatchAuditSystemAmounts(@RequestParam Map<String,Object> param)throws  Exception {
        Result res = new Result(ResultDetailMsg.OK);
        Map<String, Object> row = JSONObject.parseObject(String.valueOf(param.get("row")), Map.class);
        Object freshType = param.get("freshType");

        Object incomeSettleBeginTime = row.get("incomeSettleBeginTime");
        Object incomeSettleEndTime = row.get("incomeSettleEndTime");
        String startTime = DateFormat.ex_strDate_to_date(String.valueOf(incomeSettleBeginTime), "yyyyMMdd");
        String endTime = DateFormat.ex_strDate_to_date(String.valueOf(incomeSettleEndTime), "yyyyMMdd");

        String ids = String.valueOf(row.get("id"));
        for (String id:ids.split(",")) {//防止硬币钱箱的
            SwAuTvmBoxAmountDifference sw = swAuTvmBoxAmountDifferenceMapper.selectById(Integer.parseInt(id));
            List<Map<String, Object>> resp = JdbcUtil.exeSqlQuery("select ifnull(sum(amount),0) amount,ifnull(sum(supplement_amount),0) supplement_amount from sc_tvm_coin_opt where station_equipment_number = '" + String.valueOf(row.get("tvmCode")) + "'" +
                            " and cash_box_type='"+ sw.getCashBoxType()+"'" +
                            " and lineid=" + String.valueOf(row.get("lineCode")) + " and station_number=" + String.valueOf(row.get("stationCode")) +
                            " and opt_type = '2'"+
                            " and bookdate >='" + startTime + "' and bookdate<='" + endTime + "'"
                    , "amount,supplement_amount");
            if (null != resp && 0 != resp.size()) {
                Map<String, Object> map = resp.get(0);
                BigDecimal amount = BigDecimal.valueOf(Long.valueOf(String.valueOf(map.get("amount"))));
                SwAuTvmBoxAmountDifference swAuTvmBoxAmountDifference = new SwAuTvmBoxAmountDifference();
                swAuTvmBoxAmountDifference.setId(Integer.valueOf(id));
                if (freshType.equals("2")) {//sc
                    swAuTvmBoxAmountDifference.setScSupplemntAmount((BigDecimal) map.get("supplement_amount"));
                }
                swAuTvmBoxAmountDifference.setScUnloadAmount(amount);
                swAuTvmBoxAmountDifferenceMapper.updateById(swAuTvmBoxAmountDifference);
            }
    }
        return res;
    }
    /**
     * 票款差异审核的分钱箱-列表-数据来源替换
     * @param param
     * @return
     */
    @ApiOperation(value = "票款差异审核的分钱箱-列表-数据来源替换",notes = "票款差异审核的分钱箱-列表-数据来源替换")
    @RequestMapping("/replaceSystemAmounts")
    public Result replaceSystemAmounts(@RequestParam Map<String,String> param) throws ParseException, SQLException {
        Result res=new Result(ResultDetailMsg.OK);
        String ids = String.valueOf(String.valueOf(param.get("id")));
        String dataSource = String.valueOf(param.get("dataSource"));
        String cashBoxType = String.valueOf(param.get("cashBoxType"));
		Result clearOutAmount = getClearOutAmount(param);

		//硬币钱箱  ids  1,2  
        for(String idStr:ids.split(",")){//主要是防止硬币钱箱
            Integer id=Integer.parseInt(idStr);
//            BigDecimal sellAmount = BigDecimal.valueOf(Long.valueOf(String.valueOf(param.get("sellAmount"))));
//            BigDecimal investAmount = BigDecimal.valueOf(Long.valueOf(String.valueOf(param.get("investAmount"))));
            SwAuTvmBoxAmountDifference swAuTvmBoxAmountDifference = swAuTvmBoxAmountDifferenceMapper.selectById(id);
			String realCashBoxType = swAuTvmBoxAmountDifference.getCashBoxType();
            BigDecimal clearOutHeJiAmount=new BigDecimal(0);
            /*
            if("6".equals(cashBoxType)){ //硬币钱箱
                BigDecimal clear_out_amount =(BigDecimal)((List<Map<String,Object>>) clearOutAmount.getData()).get(0).get("clear_out_amount");
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney().add(clear_out_amount);
            }
			if("1".equals(cashBoxType)){ //硬币回收箱
                BigDecimal clear_out_amount =(BigDecimal)((List<Map<String,Object>>) clearOutAmount.getData()).get(0).get("clear_out_amount");
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney().add(clear_out_amount);
            }
			 if("2".equals(cashBoxType)){ //硬币找零箱
               
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney();
            }
            if("3".equals(cashBoxType)){ //纸币回收
                BigDecimal clear_out_paper_amount =(BigDecimal)((List<Map<String,Object>>) clearOutAmount.getData()).get(0).get("clear_out_paper_amount");
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney().add(clear_out_paper_amount);
            }
            if("4".equals(cashBoxType)){ //纸币找零
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney();
            }
			if("5".equals(cashBoxType)){ //废钞箱
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney();
            }*/
			
			if("1".equals(realCashBoxType)){ //硬币回收箱  使用实际的钱箱类型
                BigDecimal clear_out_amount =(BigDecimal)((List<Map<String,Object>>) clearOutAmount.getData()).get(0).get("clear_out_amount");
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney().add(clear_out_amount);
            }
			 if("2".equals(realCashBoxType)){ //硬币找零箱
               
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney();
            }
            if("3".equals(realCashBoxType)){ //纸币回收
                BigDecimal clear_out_paper_amount =(BigDecimal)((List<Map<String,Object>>) clearOutAmount.getData()).get(0).get("clear_out_paper_amount");
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney().add(clear_out_paper_amount);
            }
            if("4".equals(realCashBoxType)){ //纸币找零
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney();
            }
			if("5".equals(realCashBoxType)){ //废钞箱
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney();
            }

            BigDecimal sellAmount =new BigDecimal(0);
            if("1".equals(dataSource)){//人工修改
                sellAmount=swAuTvmBoxAmountDifference.getBillOrderMoney();

            }else if("2".equals(dataSource)){//sc
                sellAmount=swAuTvmBoxAmountDifference.getScUnloadAmount();

            }else if("6".equals(dataSource)){//分钱箱票款差异协查
                sellAmount=swAuTvmBoxAmountDifference.getReplyUnloadDisplayMoney();

            }
            swAuTvmBoxAmountDifference.setSystemMoney(sellAmount);
            swAuTvmBoxAmountDifference.setDiffMoney(clearOutHeJiAmount.subtract(sellAmount));
            swAuTvmBoxAmountDifference.setDataSource(dataSource);
            swAuTvmBoxAmountDifferenceMapper.updateById(swAuTvmBoxAmountDifference);
        }
        return res;
    }



    /**
     * 票款差异审核的分钱箱-列表-数据来源替换  TODO 废弃
     * @param swAuTvmBoxAmountDifference
     * @return
     */
    @RequestMapping("replaceCengJiDatasourceSwAuTvmBoxAmountDifference")
    public Result replaceCengJiDatasourceSwAuTvmBoxAmountDifference(SwAuTvmBoxAmountDifference swAuTvmBoxAmountDifference){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            SwAuTvmBoxAmountDifference swAuTvmBoxAmountDifference1 = swAuTvmBoxAmountDifferenceMapper.selectById(swAuTvmBoxAmountDifference.getId());
            SwAuTvmAmountDefference swAuTvmAmountDefference = swAuTvmAmountDefferenceMapper.selectById(swAuTvmBoxAmountDifference1.getRelationid());
            if(swAuTvmBoxAmountDifference.getDataSource().equals("1")){ //选择结账单据
                BigDecimal subtract = (swAuTvmAmountDefference.getTvmBillReceivePapaer().add(swAuTvmAmountDefference.getTvmBillReceiveCoins())).subtract((swAuTvmAmountDefference.getTvmBillNoteChange().add(swAuTvmAmountDefference.getTvmBillCoinChange())));
                swAuTvmBoxAmountDifference.setSystemMoney(subtract);
            }else if(swAuTvmBoxAmountDifference.getDataSource().equals("2")){ //选择sc
                BigDecimal subtract = swAuTvmAmountDefference.getScCashSellTicket().add(swAuTvmAmountDefference.getScCashRecharge()).subtract(swAuTvmAmountDefference.getScCashReturn());
                swAuTvmBoxAmountDifference.setSystemMoney(subtract);
            }else if(swAuTvmBoxAmountDifference.getDataSource().equals("3")){//选择lc
                BigDecimal subtract = swAuTvmAmountDefference.getLcCashSellTicket().add(swAuTvmAmountDefference.getLcCashRecharge()).subtract(swAuTvmAmountDefference.getLcCashReturn());
                swAuTvmBoxAmountDifference.setSystemMoney(subtract);
            }else if(swAuTvmBoxAmountDifference.getDataSource().equals("4")){//选择ACCc
                BigDecimal subtract = swAuTvmAmountDefference.getAccCashSellTicket().add(swAuTvmAmountDefference.getAccCashRecharge()).subtract(swAuTvmAmountDefference.getAccCashReturn());
                swAuTvmBoxAmountDifference.setSystemMoney(subtract);
            }else if(swAuTvmBoxAmountDifference.getDataSource().equals("5")){
                BigDecimal singleDeviceSysMoney = swAuTvmAmountDefference.getSingleDeviceSysMoney();
                swAuTvmBoxAmountDifference.setSystemMoney(singleDeviceSysMoney);
            }else if(swAuTvmBoxAmountDifference.getDataSource().equals("6")){
                BigDecimal singleDeviceSysMoney = swAuTvmAmountDefference.getBoxAuditSysMoney();
                swAuTvmBoxAmountDifference.setSystemMoney(singleDeviceSysMoney);
            }
            swAuTvmBoxAmountDifference.setDiffMoney(swAuTvmAmountDefference.getSystemMoney().subtract(swAuTvmAmountDefference.getActualMoney().subtract(swAuTvmAmountDefference.getSupplementMoney().add(swAuTvmAmountDefference.getHandOutMoney()))));
            swAuTvmBoxAmountDifferenceMapper.updateById(swAuTvmBoxAmountDifference);
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("替换失败");
        }

        return res;
    }



    /**
     * 编辑操作 TVM票款差异分钱箱差异审核
     * @param
     * @param swAuTvmBoxAmountDifference
     * @param
     * @return
     */
    @ApiOperation(value = "TVM票款差异分钱箱差异审核编辑", notes = "TVM票款差异分钱箱差异审核编辑")
    @PostMapping("/updateSwAuTvmBoxAmountDefference")
    @Transactional(rollbackFor = Exception.class)
    public Result updateSwAuTvmBoxAmountDefference(@RequestBody SwAuTvmBoxAmountDifference swAuTvmBoxAmountDifference){
        Result res=new Result(ResultDetailMsg.OK);
        try {

            //修改之前保存记录表 核对数据来源  1.结账单据 2.SC 3.LC 4.ACC 5.单台设备差异协查结果 6.分钱箱审核结果
            PigxUser user = SecurityUtils.getUser();
            SwAuTvmBoxAmountDifference boxAmountDifference = swAuTvmBoxAmountDifferenceMapper.selectById(swAuTvmBoxAmountDifference.getId());
            SwAuTvmBoxAmountDifferenceLog boxAmountDifferenceLog = new SwAuTvmBoxAmountDifferenceLog();
            BeanUtils.copyProperties(boxAmountDifference,boxAmountDifferenceLog);
            SwAuTvmBoxAmountDifference newBoxDefference = new SwAuTvmBoxAmountDifference();
            Result clearOutAmount = getClearOutAmountOfReplace(swAuTvmBoxAmountDifference);
            String realCashBoxType = swAuTvmBoxAmountDifference.getCashBoxType();
            BigDecimal clearOutHeJiAmount=new BigDecimal(0);
            if("1".equals(realCashBoxType)){ //硬币回收箱  使用实际的钱箱类型
                BigDecimal clear_out_amount =(BigDecimal)((List<Map<String,Object>>) clearOutAmount.getData()).get(0).get("clear_out_amount");
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney().add(clear_out_amount);
            }
            if("2".equals(realCashBoxType)){ //硬币找零箱

                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney();
            }
            if("3".equals(realCashBoxType)){ //纸币回收
                BigDecimal clear_out_paper_amount =(BigDecimal)((List<Map<String,Object>>) clearOutAmount.getData()).get(0).get("clear_out_paper_amount");
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney().add(clear_out_paper_amount);
            }
            if("4".equals(realCashBoxType)){ //纸币找零
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney();
            }
            if("5".equals(realCashBoxType)){ //废钞箱
                clearOutHeJiAmount=swAuTvmBoxAmountDifference.getActualMoney();
            }
            newBoxDefference.setId(boxAmountDifference.getId());
            if("1".equals(swAuTvmBoxAmountDifference.getDataSource())){
                newBoxDefference.setBillOrderMoney(swAuTvmBoxAmountDifference.getBillOrderMoney());
                BigDecimal billOrderMoney = swAuTvmBoxAmountDifference.getBillOrderMoney();
                billOrderMoney=billOrderMoney==null?new BigDecimal(0):billOrderMoney;
                BigDecimal subtract = clearOutHeJiAmount.subtract(billOrderMoney);
                newBoxDefference.setSystemMoney(billOrderMoney);
                newBoxDefference.setDiffMoney(subtract);
                boxAmountDifferenceLog.setOldSystemMoney(boxAmountDifference.getBillOrderMoney());
            }
            if("2".equals(swAuTvmBoxAmountDifference.getDataSource())){
                newBoxDefference.setBillOrderMoney(swAuTvmBoxAmountDifference.getScUnloadAmount());
                BigDecimal scUnloadAmount = swAuTvmBoxAmountDifference.getScUnloadAmount();
                scUnloadAmount=scUnloadAmount==null?new BigDecimal(0):scUnloadAmount;
                BigDecimal subtract = clearOutHeJiAmount.subtract(scUnloadAmount);
                newBoxDefference.setSystemMoney(scUnloadAmount);
                newBoxDefference.setDiffMoney(subtract);
                boxAmountDifferenceLog.setOldSystemMoney(boxAmountDifference.getScUnloadAmount());
            }
			 if("6".equals(swAuTvmBoxAmountDifference.getDataSource())){ 
                newBoxDefference.setBillOrderMoney(swAuTvmBoxAmountDifference.getReplyUnloadDisplayMoney());
                BigDecimal scUnloadAmount = swAuTvmBoxAmountDifference.getReplyUnloadDisplayMoney();
                scUnloadAmount=scUnloadAmount==null?new BigDecimal(0):scUnloadAmount;
                BigDecimal subtract = clearOutHeJiAmount.subtract(scUnloadAmount);
                newBoxDefference.setSystemMoney(scUnloadAmount);
                newBoxDefference.setDiffMoney(subtract);
                boxAmountDifferenceLog.setOldSystemMoney(boxAmountDifference.getReplyUnloadDisplayMoney());
            }
            boxAmountDifferenceLog.setRelationId(boxAmountDifference.getId());
            boxAmountDifferenceLog.setCreatorId(user.getUserCode());
            boxAmountDifferenceLog.setCreatorName(user.getNikeName());
            boxAmountDifferenceLog.setCreateTime(new Date());
            boxAmountDifferenceLog.setReasonRemark(boxAmountDifference.getReasonRemark());
            int b = swAuTvmBoxAmountDifferenceLogMapper.insert(boxAmountDifferenceLog);
            if(b>0){
                newBoxDefference.setDataSource("1");//人工修改
                newBoxDefference.setReasonRemark(swAuTvmBoxAmountDifference.getReasonRemark());
                swAuTvmBoxAmountDifferenceMapper.updateById(newBoxDefference);
            }
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("TVM票款差异分钱箱编辑失败");
        }
        return res;
    }


    /**
     * 查询日志记录表
     * @return
     */
    @GetMapping("/SwAuTvmBoxAmountDefferenceLogIdList/{id}/{cashBoxType}/{dataSource}")
    @ApiOperation(value = "查询记录表",notes = "查询记录表")
    public Result SwAuTvmBoxAmountDefferenceLogIdList(
            @PathVariable(value = "id") Integer relationId,
            @PathVariable(value = "cashBoxType") String cashBoxType
    ){
        Result res=new Result(ResultDetailMsg.OK);
        try {
            res.setData(swAuTvmBoxAmountDifferenceLogMapper.selectList(Wrappers.<SwAuTvmBoxAmountDifferenceLog>lambdaQuery()
                    .eq(SwAuTvmBoxAmountDifferenceLog::getRelationId,relationId)
                    .eq(SwAuTvmBoxAmountDifferenceLog::getCashBoxType,cashBoxType)));
        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_SELECT_ERROR);
            res.setMsg("查询失败");
        }
        return res;
    }

    /**
     * 批量修改差异原因
     * @param param
     * @return
     */
    @RequestMapping("/updateDiffReason")
    @ApiOperation(value = "批量修改差异原因",notes = "批量修改差异原因")
    public Result updateDifferences(@RequestParam Map<String,String> param){
        return swAuTvmBoxAmountDifferenceService.updateDifferences(param);
    }

    /**
     * 通过id列表撤回审核通过的分钱箱差异审核主页
     * @param ids ids
     * @return R
     */
    @ApiOperation(value = "通过id列表撤回审核通过的分钱箱差异审核主页", notes = "通过id列表撤回审核通过的分钱箱差异审核主页")
    @SysLog("通过id列表撤回审核通过的分钱箱差异审核主页" )
    @PutMapping("/revokeTvmBoxIds")
    public R revokeIds(@RequestParam(value = "ids") List<Integer> ids) {
        LambdaUpdateWrapper<SwAuTvmBoxAmountDifference> lambdaUpdateWrapper = Wrappers.<SwAuTvmBoxAmountDifference>lambdaUpdate()
                .set(SwAuTvmBoxAmountDifference::getAuditStatus, "0")//撤回审核状态为0
                //.set(SwAuTvmBoxAmountDifference::getAuditTime, null)
                //.set(SwAuTvmBoxAmountDifference::getAuditPersonCode, null)
                //.set(SwAuTvmBoxAmountDifference::getAuditPersonName, null) 
                .set(SwAuTvmBoxAmountDifference::getUpdateTime, new Date())
                .in(SwAuTvmBoxAmountDifference::getId,ids);
        return R.ok(swAuTvmBoxAmountDifferenceMapper.update(null,lambdaUpdateWrapper));
    }
}
